package com.example.bee_work_3.fragment.project;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.bee_work_3.webc_ontent.IntentCallBack;
import com.example.bee_work_3.fragment.ListItem;
import com.example.bee_work_3.net_request.MyJsonArray;
import com.example.bee_work_3.net_request.MyJsonObject;
import com.example.bee_work_3.R;
import com.example.bee_work_3.net_request.WS;
import com.example.bee_work_3.webc_ontent.WebActivity;

import java.util.ArrayList;
import java.util.List;

public class Fragment_Project extends Fragment {

    private int id = 0, pager = 0;
    private int lastItem = 0;

    private RecyclerView recyclerView;      //class
    private ListView listView;              //data
    private SwipeRefreshLayout swipeRefreshLayout;

    /**
     * String[]
     * 0 : name
     * 1 : id
     **/
    private List<String[]> classList = new ArrayList<>();
    private ProjectClassAdapter projectClassAdapter;
    private List<ListItem> dataList = new ArrayList<>();
    private ProjectDataAdapter projectDataAdapter;

    private CallBack callBack = new CallBack() {
        @Override
        public void onSelected(int id_tmp) {
            id = id_tmp;
            dataList.clear();
            projectDataAdapter.notifyDataSetChanged();
            pager = 0;
            getClassData();
        }
    };
    private IntentCallBack intentCallBack = new IntentCallBack() {
        @Override
        public void onIntent(ListItem item) {
            Intent intent = new Intent(getActivity(), WebActivity.class);
            intent.putExtra("title", item.getText());
            intent.putExtra("URL", item.getLink());
            intent.putExtra("id", item.getId());
            startActivity(intent);
        }
    };

    @Override
    public void onCreate(Bundle save) {
        super.onCreate(save);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStace) {
        View view = this.getLayoutInflater().inflate(R.layout.fragment_project, null);
        init(view);
        return view;
    }

    public void init(View view) {
        //数据绑定
        recyclerView = view.findViewById(R.id.project_class);
        listView = view.findViewById(R.id.project_data);
        swipeRefreshLayout = view.findViewById(R.id.project_refresh);
        swipeRefreshLayout.setColorSchemeColors(Color.GREEN, Color.BLUE, Color.YELLOW);
        swipeRefreshLayout.setRefreshing(true);
        projectClassAdapter = new ProjectClassAdapter(getActivity(), R.layout.data_item, classList, callBack);
        projectDataAdapter = new ProjectDataAdapter(getActivity(), R.layout.text_item, dataList, intentCallBack);
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.HORIZONTAL);
        listView.setAdapter(projectDataAdapter);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(projectClassAdapter);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pager = 0;
                dataList.clear();
                classList.clear();
                projectClassAdapter.notifyDataSetChanged();
                projectDataAdapter.notifyDataSetChanged();
                getClassName();
                getClassData();
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE && lastItem == (dataList.size() - 1)) {
                    getClassData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lastItem = listView.getLastVisiblePosition();
            }
        });
        getClassName();
    }

    public void getClassName() {
        WS.CallBack callBack = new WS.CallBack() {
            @Override
            public void onResult(String Json) {
                MyJsonObject object = new MyJsonObject(Json);
                MyJsonArray objectList = object.getJsonArray("data");
                List<MyJsonObject> list = objectList.getList();
                for (MyJsonObject temp : list) {
                    String[] str = {temp.getString("name"), temp.getString("id")};
                    classList.add(str);
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        projectClassAdapter.notifyDataSetChanged();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        };
        WS.load("https://www.wanandroid.com/project/tree/json")
                .addCallBack(callBack)
                .get();
    }

    public void getClassData() {
        WS.CallBack callBack = new WS.CallBack() {
            @Override
            public void onResult(String Json) {
                MyJsonObject object = new MyJsonObject(Json);
                if (object.getInt("errorCode") != 0) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "加载错误", Toast.LENGTH_SHORT).show();
                        }
                    });
                    pager = 0;
                    return;
                }
                final MyJsonObject data = object.getJsonObject("data");
                MyJsonArray datas = data.getJsonArray("datas");
                List<MyJsonObject> list = datas.getList();
                for (MyJsonObject temp : list) {
                    ListItem item = new ListItem(temp.getString("desc"), temp.getString("envelopePic")
                            , temp.getString("link"),temp.getString("niceDate"),
                            temp.getString("author"),temp.getBoolean("collect"),temp.getInt("id"));
                    dataList.add(item);
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        projectDataAdapter.notifyDataSetChanged();
                        if (data.getString("total").equals(dataList.size() + ""))
                            Toast.makeText(getActivity(), "已加载所有数据", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(getActivity(), "加载成功...", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        WS.load("https://www.wanandroid.com/project/list/" + (++pager) + "/json?cid=" + id)
                .addCallBack(callBack)
                .get();
    }

    interface CallBack {
        void onSelected(int id);
    }
}
